<template>
  <div
    class="flex flex-col h-screen font-microsoft-yahei bg-gradient-to-br from-yellow-50 to-orange-50"
  >
    <!-- 顶部标题区域 -->
    <div
      class="bg-gradient-to-r from-orange-500 to-yellow-400 text-white p-6 text-center shadow-lg relative overflow-hidden"
    >
      <!-- 装饰元素 -->
      <div class="absolute inset-0 opacity-10">
        <div class="absolute -right-10 -top-10 w-40 h-40 rounded-full bg-white"></div>
        <div class="absolute -left-20 bottom-0 w-60 h-60 rounded-full bg-white"></div>
      </div>

      <div class="flex justify-center items-center text-2xl font-bold mb-2 relative z-10">
        <span class="w-3 h-3 bg-white rounded-full mr-2 animate-pulse"></span>
        智能点餐助手
      </div>
      <p class="text-sm opacity-90 relative z-10">有什么可以为您推荐的？随时告诉我您的需求</p>
    </div>

    <!-- 主体内容区域 -->
    <div class="flex flex-1 overflow-hidden">
      <!-- 左侧历史聊天记录 -->
      <div class="w-64 bg-white border-r border-yellow-200 p-5 flex flex-col shadow-sm">
        <h3
          class="text-lg text-gray-800 font-bold mb-5 pb-2 border-b border-yellow-200 flex items-center"
        >
          <i class="fa fa-history mr-2 text-orange-400"></i> 历史聊天记录
        </h3>
        <button
          class="bg-gradient-to-r from-orange-400 to-yellow-400 text-white py-2 px-4 rounded-md text-sm cursor-pointer mb-5 hover:from-orange-500 hover:to-yellow-500 transition-all shadow-sm flex items-center justify-center"
          @click="createNewChat"
        >
          <i class="fa fa-plus-circle mr-1"></i> 开始新聊天
        </button>
        <ul class="list-none flex-1 overflow-y-auto">
          <li
            v-for="(session, index) in userChatSessions"
            :key="index"
            :class="{
              'bg-yellow-100 border-l-4 border-orange-400': currentMemoryId === session.memoryId
            }"
            class="p-3 mb-2 bg-white rounded-md cursor-pointer text-gray-800 hover:bg-yellow-50 transition-all flex items-center"
            @click="loadChatSession(session.memoryId)"
          >
            <i class="fa fa-comment-dots text-orange-400 mr-2"></i>
            <div class="font-bold text-sm">会话 #{{ session.memoryId.substr(0, 8) }}</div>
          </li>
        </ul>
      </div>

      <!-- 右侧聊天区域 -->
      <div class="flex-1 flex flex-col p-5 bg-yellow-50">
        <!-- 聊天消息容器 -->
        <div class="flex-1 overflow-y-auto pr-2 mb-4 bg-white rounded-xl shadow-sm p-4">
          <div
            v-for="(message, msgIndex) in currentChatMessages"
            :key="msgIndex"
            :class="{
              flex: true,
              'justify-end': message.sender === 'USER',
              'justify-start': message.sender === 'AI',
              'my-5': true
            }"
          >
            <div class="flex-shrink-0">
              <img
                :src="message.sender === 'USER' ? userAvatar : aiAvatar"
                alt="avatar"
                class="w-10 h-10 rounded-full mx-2 border-2 border-white shadow-sm"
              />
            </div>
            <div
              :class="{
                'bg-gradient-to-br from-orange-400 to-orange-300 text-white rounded-tl-md rounded-tr-none rounded-br-md rounded-bl-md':
                  message.sender === 'USER',
                'bg-gradient-to-br from-white to-gray-50 text-gray-800 rounded-tl-none rounded-tr-md rounded-br-md rounded-bl-md':
                  message.sender === 'AI'
              }"
              class="p-4 rounded-md leading-relaxed shadow-sm max-w-[calc(100%-15px)] relative border border-yellow-100"
            >
              <div
                v-html="message.sender === 'AI' ? md.render(message.content) : message.content"
              ></div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="relative">
          <div class="flex items-center mb-4">
            <input
              v-model="userInput"
              class="flex-1 py-3 px-5 border border-yellow-200 rounded-full text-sm outline-none focus:border-orange-400 focus:shadow-md transition-all bg-white pl-12 shadow-sm"
              placeholder="输入您的点餐需求...（例如：推荐川菜餐厅）"
              @keyup.enter="sendMessage"
            />
            <i class="fa fa-smile-o text-gray-400 absolute left-7 top-1/2 -translate-y-1/2"></i>
            <button
              class="bg-gradient-to-r from-orange-400 to-yellow-400 text-white py-3 px-6 rounded-full text-sm cursor-pointer ml-2 hover:from-orange-500 hover:to-yellow-500 transition-all shadow-sm flex items-center"
              @click="sendMessage"
            >
              <i class="fa fa-paper-plane mr-1"></i> 发送
            </button>
          </div>

          <!-- 快捷按钮放在输入框下方 -->
          <div class="flex gap-2">
            <button
              class="flex-1 py-2.5 px-3 bg-white text-orange-400 border border-yellow-200 rounded-full text-sm cursor-pointer hover:border-orange-300 hover:bg-yellow-50 transition-all shadow-sm flex items-center justify-center"
              @click="handleQuickBtn('推荐菜品')"
            >
              <i class="fa fa-cutlery mr-1"></i> 推荐菜品
            </button>
            <button
              class="flex-1 py-2.5 px-3 bg-white text-orange-400 border border-yellow-200 rounded-full text-sm cursor-pointer hover:border-orange-300 hover:bg-yellow-50 transition-all shadow-sm flex items-center justify-center"
              @click="handleQuickBtn('推荐餐厅')"
            >
              <i class="fa fa-building mr-1"></i> 推荐餐厅
            </button>
            <button
              class="flex-1 py-2.5 px-3 bg-white text-orange-400 border border-yellow-200 rounded-full text-sm cursor-pointer hover:border-orange-300 hover:bg-yellow-50 transition-all shadow-sm flex items-center justify-center"
              @click="handleQuickBtn('推荐搭配')"
            >
              <i class="fa fa-coffee mr-1"></i> 推荐搭配
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import axios from 'axios'
import { v4 as uuidv4 } from 'uuid'
import MarkdownIt from 'markdown-it'

// 初始化 MarkdownIt 实例
const md = new MarkdownIt()

// 模拟头像
import userAvatar from './image/用户.png'
import aiAvatar from './image/人工智能.png'

// 状态管理
const userChatSessions = ref([])
const currentChatMessages = ref([])
const currentMemoryId = ref(null)
const userInput = ref('')
const loadingSessions = ref(false)
const errorMessage = ref('')
const isStreaming = ref(false)

// 初始化获取历史会话
onMounted(() => {
  fetchUserChatSessions()
})

// 获取授权头
const getAuthHeader = () => {
  const token = window.localStorage.getItem('Usertoken')
  return token ? { Authorization: token } : {}
}

// 获取历史聊天记录
const fetchUserChatSessions = async () => {
  loadingSessions.value = true
  try {
    const response = await axios.get('http://localhost:8080/res/user', {
      headers: getAuthHeader()
    })
    if (Array.isArray(response.data)) {
      userChatSessions.value = response.data
    } else {
      errorMessage.value = '历史会话数据格式异常'
    }
  } catch (error) {
    if (error.response && error.response.status === 401) {
      errorMessage.value = '身份验证失败，请重新登录'
      // 这里可以添加跳转到登录页面的逻辑
    } else {
      errorMessage.value = `获取历史记录失败：${error.message}`
    }
  } finally {
    loadingSessions.value = false
  }
}

// 加载指定会话
const loadChatSession = async (memoryId) => {
  try {
    const response = await axios.get(`http://localhost:8080/res/memory/${memoryId}`, {
      headers: getAuthHeader()
    })
    currentMemoryId.value = memoryId
    if (response.data && Array.isArray(response.data.messages)) {
      currentChatMessages.value = response.data.messages
      nextTick(() => {
        scrollToBottom()
      })
    } else {
      errorMessage.value = '聊天记录数据格式异常'
      currentChatMessages.value = []
    }
  } catch (error) {
    if (error.response && error.response.status === 401) {
      errorMessage.value = '身份验证失败，请重新登录'
      // 这里可以添加跳转到登录页面的逻辑
    } else {
      errorMessage.value = '加载聊天记录失败'
      currentChatMessages.value = []
    }
  }
}

// 发送消息
const sendMessage = async () => {
  if (!userInput.value.trim()) return

  if (!currentMemoryId.value) {
    currentMemoryId.value = uuidv4()
  }

  const chatForm = {
    memoryId: currentMemoryId.value,
    message: userInput.value
  }

  try {
    // 先添加用户消息
    currentChatMessages.value.push({
      sender: 'USER',
      content: userInput.value,
      timestamp: new Date().getTime()
    })
    userInput.value = ''
    scrollToBottom()
    isStreaming.value = true

    // 调用后端接口，添加授权头
    const response = await fetch('http://localhost:8080/res/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...getAuthHeader()
      },
      body: JSON.stringify(chatForm)
    })

    if (response.status === 401) {
      errorMessage.value = '身份验证失败，请重新登录'
      isStreaming.value = false
      // 这里可以添加跳转到登录页面的逻辑
      return
    }

    const reader = response.body.getReader()
    const decoder = new TextDecoder('utf-8')

    // 添加 AI 消息占位
    const aiMessage = {
      sender: 'AI',
      content: '',
      timestamp: new Date().getTime()
    }
    currentChatMessages.value.push(aiMessage)
    scrollToBottom()

    // 流式接收响应
    while (true) {
      const { done, value } = await reader.read()
      if (done) break
      const chunk = decoder.decode(value)
      aiMessage.content += chunk
      // 触发响应式更新
      currentChatMessages.value = [...currentChatMessages.value]
      scrollToBottom()
    }

    isStreaming.value = false
    // 更新历史会话
    await fetchUserChatSessions()
  } catch (error) {
    errorMessage.value = '发送消息失败'
    isStreaming.value = false
  }
}

// 创建新会话
const createNewChat = () => {
  currentMemoryId.value = uuidv4()
  currentChatMessages.value = []
  userInput.value = '你好'
  sendMessage()
}

// 快捷按钮处理
const handleQuickBtn = (text) => {
  userInput.value = text
  sendMessage()
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    const container = document.querySelector('.flex-1.overflow-y-auto.pr-2.mb-4')
    if (container) {
      container.scrollTop = container.scrollHeight
    }
  })
}
</script>

<style scoped>
@tailwind base;
@tailwind components;
@tailwind utilities;

@font-face {
  font-family: 'Microsoft YaHei';
  src: local('Microsoft YaHei');
}

/* 滚动条样式 */
.flex-1.overflow-y-auto.pr-2.mb-4::-webkit-scrollbar {
  width: 6px;
}

.flex-1.overflow-y-auto.pr-2.mb-4::-webkit-scrollbar-track {
  background: #fff8e1;
}

.flex-1.overflow-y-auto.pr-2.mb-4::-webkit-scrollbar-thumb {
  background: #ffe0b2;
  border-radius: 3px;
}

.flex-1.overflow-y-auto.pr-2.mb-4::-webkit-scrollbar-thumb:hover {
  background: #ffcc80;
}

/* 引入 Font Awesome */
@import url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css');
</style>
